package cn.test.server;

import cn.test.utils.ByteBufUtil;
import cn.test.utils.ByteHexUtil;
import cn.test.utils.DeviceData;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/***
 *
 *
 * @Author: SJie
 * Date: 2019/12/19 下午5:44
 * Description:
 *
 */

public class DataHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Server1:" + "channelInactive");

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.out.println(msg.toString());
//        return;
        byte[] data = (byte[]) msg;
        if (ByteHexUtil.byteToHex(data[0]) == 0x00) {
            System.out.println("设备号应答：" + ByteHexUtil.byteToBin(data[1]));
            String deviceKey = ByteHexUtil.byteToBin(data[1]);
            DeviceData.setDeviceKey(ctx.channel(), deviceKey);
        }
        System.out.println("数据");
        System.out.println(ByteHexUtil.bytesToHexStr(data));


    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    public static void main(String[] args) {
        byte b = 16;
        String s = Long.toString(b & 0xff, 2);
        System.out.println(s);

    }
}
